package com.ruoyi.common.utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class TelnetUtil {
    static String ips = "117.94.116.149:4516\n" +
            "221.10.217.161:4585\n" +
            "223.247.31.121:4516\n" +
            "36.33.22.204:4526\n" +
            "182.109.184.24:4527\n" +
            "112.114.89.111:4532\n" +
            "106.56.90.3:4565\n" +
            "36.6.63.91:4526\n" +
            "106.226.237.150:4572\n" +
            "106.112.126.128:4541\n" +
            "117.82.248.230:4536\n" +
            "223.247.165.232:4545\n" +
            "59.57.148.115:4502\n" +
            "36.57.94.246:4527\n" +
            "114.229.4.207:4503";
    /**
     * 测试telnet 机器端口的连通性
     * @param hostname
     * @param port
     * @param timeout
     * @return
     */
    public static boolean telnet(String hostname, int port, int timeout){
        Socket socket = new Socket();
        boolean isConnected = false;
        try {
            socket.connect(new InetSocketAddress(hostname, port), timeout); // 建立连接
            isConnected = socket.isConnected(); // 通过现有方法查看连通状态
        } catch (IOException e) {
            System.out.println("false");        // 当连不通时，直接抛异常，异常捕获即可
        }finally{
            try {
                socket.close();   // 关闭连接
            } catch (IOException e) {
                System.out.println("false");
            }
        }
        return isConnected;
    }

    public static void main(String[] args) {
        int timeout = 200;
        String[] arr = ips.split("\n");
        for (String ipStr : arr) {
            String[] temp = ipStr.trim().split(":");
            boolean bbb = telnet(temp[0], Integer.parseInt(temp[1]), timeout);
            System.out.println("telnet "+ temp[0] + " " + Integer.parseInt(temp[1]) + "\n==>isConnected: " + bbb);
        }

    }
}
